<template>
  <div class="Advertising">
    <el-menu router default-active="1" class="Ecp-tab-menu" mode="horizontal">
      <el-menu-item route='/supply_manage/supplySet' index="1">供应商名称</el-menu-item>
    </el-menu>
    <div class="Advertising__content">
      <header class="Advertising__header">
        <!-- <div class="Advertising__header__right">
          <el-button type="primary">搜索</el-button><br>
          <nuxt-link style="color: #409eff;padding:8px;" to='/advertising/add/0'>新增广告</nuxt-link>
        </div> -->
        <div class="Advertising__header__left">
          <el-button style="float:right;z-index:10;" @click.native="openDialog" type="primary">修改路线名称</el-button>
          <div class="Advertising__header__group" style="margin-bottom:15px;margin-right:122px;">
            <div class="Advertising__header__item">
              <span class="Advertising__header__item__label">开始配送时间</span>
              <el-time-select style="width:128px;" size="mini" v-model="startTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00'
                }"
                placeholder="设置开始时间">
              </el-time-select>
            </div>
            <div class="Advertising__header__item" style="margin-left:40px;">
              <span class="Advertising__header__item__label">结束配送时间</span>
              <el-time-select style="width:128px;" size="mini" v-model="endTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                  minTime: startTime
                }"
                placeholder="选择日期时间">
              </el-time-select>
            </div>
          </div>
          <div class="Advertising__header__group">
            <div class="Advertising__header__item">
              <span class="Advertising__header__item__label">配送路线</span>
              <el-tag
                :key="key"
                :style="{'border-color':Colors[key]}"
                v-for="(tag, key) in myRouters"
                @click.native="selectRouter(key)"
                :closable="routerKeySel == key"
                :class="{'tag-sel': routerKeySel == key}"
                :disable-transitions="false"
                @close="removeRouter(key)">
                {{tag.roadName}}
              </el-tag>
              <!-- addtag -->
              <el-button @click="addtRouter" type="primary" plain>添加</el-button>
            </div>
          </div>
        </div>
      </header>
      <div class="Advertising__map">
        <div ref="mapContainer" :class="{'plus-circle':plusNodeStatus}" id='container' style="height:412px;width:100%;"></div>
        <div class="Advertising__map__toolbar">
          <el-button :disabled="myRouters.length==0"
            :type="myRouters.length==0?'info':'primary'"
            :icon="plusNodeStatus?'el-icon-check':''" size="mini"
            @click.native="setPlusNodeStatus">添加节点</el-button>
          <el-button :disabled="myRouters.length==0"
            :type="myRouters.length==0?'info':'primary'"
            :icon="removeNodeStatus?'el-icon-minus':''"
            size="mini" @click.native="setRemoveNodeStatus">删除节点</el-button>
        </div>
      </div>
      <div class="Advertising__bottom">
        <el-button type="primary" round @click="$router.replace('/supply_manage')">取消</el-button>
        <el-button type="primary" @click.native="saveSupplyRoadData" round >保存</el-button>
      </div>
    </div>
    <p style="padding:30px 20px;line-height:1.8;color:#666;">
      1. 区域操作：<br>
      (1) 新增节点：点击新增节点按钮，然后在地图上单击，就放一下一个节点<br>
      (2) 编辑节点：点击编辑节点按钮，可以拖拽地图上的节点，用来更换位置<br>
      (3) 删除节点：点击删除节点按钮，点击地图上的节点，就删除该节点<br>
      (4) 删除地区，点击路线中某个区域，点击右上角操作按钮，即可删除该区域<br>
      (5) 不同路线区域相叠加时，加深叠加区域颜色
    </p>
    <!-- 修改路线名称 -->
    <el-dialog class="Advertising__dialog" width="400px" top="100px" title="修改路线名称" :visible.sync="dialog.show">
      <el-table :height="getTableHeight" :data="dialog.list">
        <!-- <el-table-column property="id" label="ID" width="100"></el-table-column> -->
        <el-table-column property="roadName" label="原名称" width="200"></el-table-column>
        <el-table-column label="修改后名称">
          <template slot-scope="scope">
            <el-input v-model="scope.row.newName" placeholder="请输入修改后名称"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialog.show = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="updatetRouterName">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {findRoadList, addRoadPoint} from '~/api'
import {Colors, uuid} from '~/utils'

let MyMap = ''

  export default {
    data() {
      return {
        Colors,
        plusNodeStatus: false,
        removeNodeStatus: false,
        circleChangeStatus: false,
        routerKeySel: 0,
        roadList: [],
        myRouters: [],
        zoom: 11,
        center: [121.486377,31.204694],
        userId: '',
        supplyId: '',
        startTime: '',
        endTime: '',
        searchData: {
          title:'',
        },
        dialog: {
          list: [],
          show: false
        }
      }
    },
    async asyncData ({app}) {

    },
    mounted() {
      this.findRoadList()
      // this.mapInit()

    },
    methods: {
      async saveSupplyRoadData() {
        console.log(this.roadList)
        let roadList = []
        this.roadList.map(item => {
          let data = {
            "roadName": item.roadName,
            "supplyId": item.supplyId,
            "userId": item.userId,
            "useAble": item.useAble,
            "pointRoadList": item.pointRoadList
          }
          if (item.id) {
            data.id = item.id
          }
          roadList.push(data)
        })
        const res = await addRoadPoint(this, roadList)
        console.log(res)
      },
      async findRoadList () {
        const res = await findRoadList(this)
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        this.roadList = res.data.goodsOrderGoodsList
        this.userId = res.data.goodsOrderGoodsList[0].userId
        this.supplyId = res.data.goodsOrderGoodsList[0].supplyId
        // 地图初始化
        this.mapInit()
      },
      mapInit () {
        MyMap = new window.AMap.Map('container', {
          zoom: this.zoom,
          center: this.center
        })
        MyMap.plugin(['AMap.ToolBar', 'AMap.CircleEditor'],() => {//异步同时加载多个插件
          MyMap.addControl(new AMap.ToolBar())
        })
        // 添加节点事件
        MyMap.on('click', (e) => {
          // console.log(e.target.CLASS_NAME)
          if (!this.plusNodeStatus) return
          this.plusNodeStatus = !this.plusNodeStatus
          // 添加节点
          const center = [e.lnglat.getLng(), e.lnglat.getLat()]
          const radius = 5000
          const routerKey = this.routerKeySel
          const roadId = this.roadList[routerKey].id
          this.roadList[routerKey].pointRoadList.push({longitude:center[0],latitude:center[1], roadId, radius})
          this.newCircle({center, radius, routerKey})
        })

        MyMap.on('complete', () => {
          // 地图图块加载完成后触发
          this.myRouters = []
          this.roadList.map((router, routerKey) => {
            this.myRouters.push({
              roadName: router.roadName,
              circles:[]
            })
            router.pointRoadList.map(item => {
              this.newCircle({center:[item.longitude, item.latitude], radius: item.radius, routerKey})
            })
          })
        })
      },
      newCircle({center, radius=5000, routerKey}) {
        const strokeStyle = routerKey == this.routerKeySel ? 'dashed':'solid'
        let Circle = new AMap.Circle({
          map: MyMap,
          center: center,// 圆心位置
          radius: radius, //半径
          strokeColor: this.Colors[routerKey], //线颜色
          strokeStyle: strokeStyle,
          strokeDasharray: [10,10],
          strokeOpacity: 1, //线透明度
          strokeWeight: 3, //线粗细度
          fillColor: this.Colors[routerKey], //填充颜色
          fillOpacity: 0.35,//填充透明度
          zIndex: 50
        })

        const circleKey = uuid()
        // 设置自有属性
        Circle.setExtData({routerKey, circleKey})
        MyMap.add(Circle)

        // 绑定点击事件方法
        Circle.on('click',(e) => {
          const nodeRouter = e.target.getExtData()['routerKey']
          if ( nodeRouter != this.routerKeySel) return
          const nodeKey = e.target.getExtData()['circleKey']
          // 获取选中的节点对象
          let node = this.myRouters[this.routerKeySel].circles.filter(node=>node.circleKey==nodeKey)[0]
          if (node.status == 'static') {
            node.status = 'edit'
            node.editor.open()
          } else if (node.status == 'edit') {
            node.status = 'static'
            node.editor.close()
          } else if (node.status == 'delete') {
            this.$confirm('确定删除此节点？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.myRouters[this.routerKeySel].circles.map((node, index) => {
                if (node.circleKey != nodeKey) return
                // 修改原始数据
                MyMap.remove(node.circle)
                this.myRouters[this.routerKeySel].circles.splice(index, 1)
                this.roadList[this.routerKeySel].pointRoadList.splice(index, 1)
              })
            }).catch(() => {
              console.log('取消删除节点')
            })
          }
        })
        Circle.on('change', (e) => {
          if (this.circleChangeStatus) return
          // console.log(e)
          this.circleChangeStatus = true
          setTimeout(() => {
            this.circleChangeStatus = false
            const nodeRouter = e.target.getExtData()['routerKey']
            if ( nodeRouter != this.routerKeySel) return
            const nodeKey = e.target.getExtData()['circleKey']

            const nodeOption = e.target.getOptions()
            const radius = nodeOption.radius
            const {lng, lat} = nodeOption.center
            this.myRouters[this.routerKeySel].circles.map((node, index) => {
              if (node.circleKey != nodeKey) return
              // 修改原始数据
              this.myRouters[this.routerKeySel].circles[index].radius = radius
              this.myRouters[this.routerKeySel].circles[index].center = [lng, lat]
              this.roadList[this.routerKeySel].pointRoadList[index].radius = radius
              this.roadList[this.routerKeySel].pointRoadList[index].longitude = lng
              this.roadList[this.routerKeySel].pointRoadList[index].latitude = lat
              // console.log(this.roadList)
            })
            // this.roadList
          }, 1000);
        })

        // 圆编辑器
        const editor = new AMap.CircleEditor(MyMap, Circle)
        let editorStatus = 'static'
        if (routerKey == this.routerKeySel) {
          editorStatus = 'edit'
          editor.open()
        }
        // 存储节点信息
        // 圆心、半径、路线ID、节点ID、节点元素、节点编辑器、节点状态【编辑/edit、删除/delete、正常/static】
        this.myRouters[routerKey].circles.push({
          center, radius, routerKey, circleKey, editor,
          circle: Circle,
          status: editorStatus
        })
      },
      setPlusNodeStatus () {
        // 进入增加节点状态
        this.plusNodeStatus = !this.plusNodeStatus
        if (!this.removeNodeStatus) return
        this.removeNodeStatus = !this.removeNodeStatus
        this.myRouters[this.routerKeySel].circles.map(node => {
          node.status = 'static'
          node.editor.close()
          node.circle.setOptions({strokeColor:this.Colors[this.routerKeySel]})
        })
      },
      setRemoveNodeStatus() {
        // 进入删除节点状态
        this.removeNodeStatus = !this.removeNodeStatus
        this.plusNodeStatus = false
        const status = this.removeNodeStatus ? 'delete' : 'static'
        const strokeColor = this.removeNodeStatus ? '#f00' : this.Colors[this.routerKeySel]
        this.myRouters[this.routerKeySel].circles.map(node => {
          node.status = status
          node.editor.close()
          node.circle.setOptions({strokeColor})
        })
      },
      removeRouter(key){
        // 初始化数据
        this.$confirm(`确定删除此路线？（包含）${this.myRouters[this.routerKeySel].circles.length}个节点`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // const res = await deleteRoadList(this, this.roadList[key].id)
          // if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})

          this.plusNodeStatus = false
          this.removeNodeStatus = false
          this.myRouters.splice(this.routerKeySel, 1)
          // 修改原始数据
          this.roadList.splice(this.routerKeySel, 1)
          this.routerKeySel = 0

          // 保留地图移动缩放状态
          this.zoom = MyMap.getZoom()
          const {lng, lat} =  MyMap.getCenter()
          this.center = [lng, lat]
          // 初始化地图
          this.mapInit()
        }).catch(() => {
          console.log('取消删除路线')
        })
      },
      addtRouter() {
        if (this.myRouters.length == this.Colors.length) {
          this.Colors.push(this.randomColor())
        }
        // 新增路线
        // 路线名称
        this.$prompt("请输入路线名称", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[\u4E00-\u9FA5\uF900-\uFA2D\w]+$/,
          inputErrorMessage: "路线名不能为空"
        }).then(async ({ value }) => {
          this.myRouters.push({
            "roadName": value,
            circles:[]
          })
          this.plusNodeStatus = true
          this.routerKeySel = this.myRouters.length-1
          // 修改原始数据
          this.roadList.push({
            "roadName": value,
            "supplyId": this.supplyId,
            "userId": this.userId,
            "useAble": 0,
            pointRoadList: []
          })
          this.selectRouter(this.routerKeySel)
        }).catch(() => {
          console.log('取消新增路线')
        });
      },
      selectRouter(key) {
        // 选中路线
        this.routerKeySel = key
        this.myRouters.map((routers, index) => {
          if (routers.circles.length == 0) return this.plusNodeStatus = true
          const strokeStyle = index == key ? 'dashed':'solid'
          const strokeColor = this.Colors[index]
          routers.circles.map(node => {
            node.editor.close()
            node.circle.setOptions({strokeColor, strokeStyle})
          })
        })
      },
      randomColor() {
        const r = Math.floor(Math.random()*220+30)
        const g = Math.floor(Math.random()*220+30)
        const b = Math.floor(Math.random()*220+30)
        return `rgb(${r},${g},${b})`
      },
      openDialog() {
        this.dialog.list = []
        this.roadList.map(item => this.dialog.list.push({
          id: item.id,
          roadName: item.roadName,
          newName: item.roadName
        }))
        this.dialog.show = true
      },
      updatetRouterName() {
        this.dialog.list.map((item, index) => {
          this.roadList[index].roadName = item.newName
          this.myRouters[index].roadName = item.newName
          this.dialog.show = false
        })
      }
    },
    computed: {
      getTableHeight() {
        return this.$store.state.innerHeight-312
      }
    }
  }
</script>

<style lang="scss" scoped>
.Advertising {
  background-color: #f5f9fe;
  &__dialog {
    & /deep/ {
      .el-input__inner {
        line-height: 28px;
        height: 28px;
      }
      .el-dialog__body {
        padding: 0;
      }
      .el-table td {
        padding: 6px 0;
      }
    }
  }
  &__map {
    position: relative;
    & /deep/ {
      canvas {
        cursor: url(http://webapi.amap.com/theme/v1.3/openhand.cur),default;
      }
      .plus-circle {
        canvas {
          cursor: crosshair;
        }
      }
    }

    &__toolbar {
      position: absolute;
      top: 15px;
      right: 15px;
      font-size: 12px;
      padding: 10px;
      &__btn {
        height: 28px;
        line-height: 28px;
        background-color: #409eff;
        color: #FFF;
        border: 0;
        outline: none;
        padding-left: 5px;
        padding-right: 5px;
        border-radius: 3px;
        margin-bottom: 4px;
        cursor: pointer;
        &:not(:last-child) {
          margin-right: 10px;
        }
      }
    }
  }
  &__content {
    background-color: #fff;
  }
  &__header {
    border-bottom: 1px solid #f2f2f2;
    color: #191919;
    font-size: 16px;
    line-height: 18px;
    &__group {
      padding-left: 42px;
      position: relative;
      &::before{
        content: "";
        display: block;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: #84dba7;
        position: absolute;
        top: 14.5px;
        left: 18px;
      }
    }
    &__item {
      line-height: 25px;
      display: inline-block;
      padding-top: 4px;
      padding-bottom: 4px;
      & /deep/ {
        .el-input__icon {
          line-height: 25px;
        }
        .el-input__inner, .el-input--suffix{
          height: 25px;
          line-height: 25px;
          background-color: #f0f5fb;
          border: none;
          border-radius: 8px;
        }
      }
      &__label {
        padding-right: 25px;
      }
      &__input {
        border: none;
        width: 128px;
        height: 25px;
        background-color: #f0f5fb;
        border-radius: 9px;
        padding-left: 15px;
        &:focus {
          outline: none;
        }
      }
    }
    &__left {
      padding: 15px 0 5px;
      margin-right: 20px;
      & /deep/ {
        .el-button--text {
          font-size: 16px;
          padding: 8px 18px;
        }
        .el-button--primary {
          padding: 5px 18px;
          margin-bottom: 10px;
        }
        .el-tag {
          height: 26px;
          margin-bottom: 10px;
          line-height: 26px;
          margin-right: 15px;
          background-color: #f0f5fb;
          color: #999;
          cursor: pointer;
        }
        .tag-sel {
          background-color: rgba(64, 158, 255, .1);
          color: #409eff;
        }
      }
    }
    &__right {
      float: right;
      text-align: center;
      padding: 15px 26px;
      & /deep/ {
        .el-button--primary {
          font-size: 16px;
          border-radius: 10px;
          padding: 8px 26px;
          margin-bottom: 24px;
        }
        .el-button--text {
          font-size: 16px;
          padding: 8px 26px;
        }
      }
    }
  }
  &__bottom {
    margin-top: 24px;
    line-height:50px;
    padding-right: 30px;
    text-align:right;
    .el-button--primary {
      font-size: 18px;
      padding: 12px 40px;
      border-radius: 22px;
    }
  }
}
</style>
